local io_base = require('io_base')
local io_client = require('io_client')

if not io_base then
	print('require io_base fail')
	os.exit(-1)
end

if not io_client then
	print('require io_client fail')
	os.exit(-1)
end

print('io_base version:', io_base.version())
print('io_client version:', io_client.version())
local IO_EVENT_UNKNOW = io_base.IO_EVENT_UNKNOW
local IO_EVENT_ACCEPT = io_base.IO_EVENT_ACCEPT
local IO_EVENT_READ = io_base.IO_EVENT_READ
local IO_EVENT_WRITE = io_base.IO_EVENT_WRITE
local IO_EVENT_ERROR = io_base.IO_EVENT_ERROR
local IO_EVENT_CLOSE = io_base.IO_EVENT_CLOSE
local IO_EVENT_SIGNAL = io_base.IO_EVENT_SIGNAL
local IO_EVENT_CTRL = io_base.IO_EVENT_CTRL

local base, err = io_base.new('echo-serv', '127.0.0.1', 8888)
if not base then
	print('err:', err)
	os.exit(-1)
end

local nums = 0
local timeout = -1
while true do
	nums, err = base:loop(timeout)
	print('nums:', nums)
	if err then
		print('err:', err)
		break
	end

	while true do
		local event, obj = base:next_event()
		if not event then
			break
		end

		if event == IO_EVENT_ACCEPT then
			print('accent event')
			local obj, err = base:accept()
			if not obj then
				print('err:', err)
				break
			end
		elseif event == IO_EVENT_SIGNAL then
			print('signal event')
		elseif event == IO_EVENT_CTRL then
			print('ctrl event')
		elseif event == IO_EVENT_ERROR then
			print('error event')
			io_client.term(obj)
		elseif event == IO_EVENT_CLOSE then
			print('close event')
			io_client.term(obj)
		elseif event == IO_EVENT_READ then
			local data, err = io_client.read(obj)
			if not data then
				print('read fail:', err)
				io_client_term(obj)
			end
			print('data:', data)
			io_client.write(obj, data)
		elseif event == IO_EVENT_WRITE then
			io_client.write(obj)
		else
			print('unknow event')
		end
	end
end
